package com.bckj.fastboot.security.configuration;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.bckj.fastboot.security.StpUserUtil;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Objects;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(FastSaTokenProperties.class)
public class FastSaTokenConfiguration implements WebMvcConfigurer {

    private final FastSaTokenProperties fastSaTokenProperties;


    // 注册 Sa-Token 拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor(handle -> {
            //判断是否是feign请求
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            if ("feign".equals(request.getHeader("xyz"))) {
                //放行
                return;
            }
            //多账号体系认证模式下，校验是否登陆
            if (!(StpUtil.isLogin() || StpUserUtil.isLogin())) {
                throw new SaTokenException("请登录后再访问接口");
            }
        })).addPathPatterns("/**");
    }

    @PostConstruct
    public void init() {
        SaTokenConfig userConfig = fastSaTokenProperties.getCustom().get("user");
        if (userConfig != null) {
            StpUserUtil.stpLogic.setConfig(userConfig);
        }
    }

}
